package com.aaa.member.util;

import com.aaa.member.entity.TbMember;
import com.aaa.member.service.TbMemberService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

public class MyRealm extends AuthorizingRealm {

    @Autowired
    private TbMemberService memberService;
    /**
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获取收集到的用户名
        String username = (String) authenticationToken.getPrincipal();
        //根据用户名查询用户信息
        TbMember member =memberService.selectbyusername(username);
        //判断是否为空 为空则说明账号不存在
        if (member==null){
            throw new AccountException();
        }
        //获取密码
        String password=member.getPassword();
        System.out.println("MyRealm"+username);
        System.out.println("MyRealm"+password);
        //获取盐值
        String salt=member.getPwSalt();
        System.out.println("数据库盐值"+salt);
        //第一个参数:用户信息（认证成功后subject.getPrincipal()获取该对象）
        //第二个参数：密码（加密）
        //第三个参数：盐值
        //最后一个时参数当前运行类的名称
        // 用户名正确时，把加密加盐后的密码和盐值都交给SecutiryManager 进行认证
        return new SimpleAuthenticationInfo(member,password, ByteSource.Util.bytes(salt),this.getName());
    }
}
